package com.zuihai.app.mvp.ui.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

import com.blankj.utilcode.util.LogUtils;
import com.zuihai.app.mvp.constant.DetailConstant;
import com.zuihai.app.mvp.model.entity.mainhome.SubclassDataSupport;
import com.zuihai.app.mvp.ui.activity.detail.DetailContainerActivity;

import com.zuihai.app.mvp.ui.widget.MyToastPK;

import org.litepal.crud.DataSupport;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/7/11 0011.
 */

public class AppUtils {

    private AppUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");

    }

    /**
     * 获取应用程序名称
     */
    public static String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * base64字符串转文件
     *
     * @param base64
     * @return
     */
    public static File base64ToFile(String base64) {
        File file = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date curDate = new Date(System.currentTimeMillis());
        String timeStr = formatter.format(curDate);
        String fileName = "/release/record/" + timeStr + ".jpg";

        FileOutputStream out = null;
        try {
            // 解码，然后将字节转换为文件
            file = new File(Environment.getExternalStorageDirectory(), fileName);
            if (!file.exists())
                file.createNewFile();
            byte[] bytes = Base64.decode(base64, Base64.DEFAULT);// 将字符串转换为byte数组
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            out = new FileOutputStream(file);
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread); // 文件写操作
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 保存位图到本地
     *
     * @param bitmap
     * @return void
     */
    public static File saveImage(Bitmap bitmap) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date curDate = new Date(System.currentTimeMillis());
        String timeStr = formatter.format(curDate);
        String fileName = Environment.getExternalStorageDirectory()+"/release/record/" + timeStr + ".jpg";

        File file = new File(fileName);
        FileOutputStream fileOutputStream = null;
        //文件夹不存在，则创建它
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            fileOutputStream = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            LogUtils.e("保存成功" + fileName);
            fileOutputStream.close();
            return file;
        } catch (Exception e) {
            LogUtils.e("保存图片失败: " + e.toString());
            return null;
        }
    }

    public static File byte2File(byte[] buf) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date curDate = new Date(System.currentTimeMillis());
        String timeStr = formatter.format(curDate);
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Pictures";
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + timeStr + ".jpg");
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    public static void intentDetail(Context context, String type, String detailId) {
        List<SubclassDataSupport> allHomeColus = DataSupport.findAll(SubclassDataSupport.class);
        for (int i = 0; i < allHomeColus.size(); i++) {
            if (allHomeColus.get(i).getSubitem_id().equals(type)) {
                if (allHomeColus.get(i).getLeibie() == 1) {
                    DetailContainerActivity.
                            launchActivity(context,
                                    DetailConstant.HEADLINE_TYPE, type, detailId);

                } else if (allHomeColus.get(i).getLeibie() == 2) {
                    DetailContainerActivity.
                            launchActivity(context,
                                    DetailConstant.PICTURE_TYPE, detailId);
                } else {
                    MyToastPK.showSuccess("该栏目暂不支持跳转", context);
                }
            }
        }

    }

    public static void intentDetail(Context context, String type, String detailId, boolean isDraft) {
        List<SubclassDataSupport> allHomeColus = DataSupport.findAll(SubclassDataSupport.class);
        for (int i = 0; i < allHomeColus.size(); i++) {
            if (allHomeColus.get(i).getSubitem_id().equals(type)) {
                if (allHomeColus.get(i).getLeibie() == 1) {
                    DetailContainerActivity.
                            launchActivity(context,
                                    DetailConstant.HEADLINE_TYPE, type, detailId, isDraft);

                } else if (allHomeColus.get(i).getLeibie() == 2) {
                    DetailContainerActivity.
                            launchActivity(context,
                                    DetailConstant.PICTURE_TYPE, type, detailId, isDraft);
                } else {
                    MyToastPK.showSuccess("该栏目暂不支持跳转", context);
                }
            }
        }

    }


}